package com.DAO;



import com.DBUtil.DBUtil;
import com.entity.Goods;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao{
    
    public List<Goods> getAllGoods() {
        List<Goods> goodsList = new ArrayList<>();
        String sql = "SELECT * FROM GoodsInfo";
        
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            
            while (rs.next()) {
                Goods goods = new Goods();
                goods.setGid(rs.getInt("gid"));
                goods.setGname(rs.getString("gname"));
                goods.setGnum(rs.getInt("gnum"));
                goods.setGprice(rs.getDouble("gprice"));
                goods.setGstatus(rs.getBoolean("gstatus"));
                goodsList.add(goods);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return goodsList;
    }
    
    public boolean deleteGoods(int gid) {
        String sql = "DELETE FROM GoodsInfo WHERE gid = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, gid);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean updateGoods(Goods goods) {
        String sql = "UPDATE GoodsInfo SET gname=?, gnum=?, gprice=?, gstatus=? WHERE gid=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, goods.getGname());
            pstmt.setInt(2, goods.getGnum());
            pstmt.setDouble(3, goods.getGprice());
            pstmt.setBoolean(4, goods.getGstatus());
            pstmt.setInt(5, goods.getGid());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
} 